package pl.kosmowska.ewelina.server.dao;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import pl.kosmowska.ewelina.server.jdo.InvestmentData;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;



public class InvestmentDataDAO extends JdoDAOImpl<InvestmentData> {


	private static final Logger log = Logger.getLogger(InvestmentDataDAO.class
			.getName());

	public InvestmentData findInvestmentData(String id) {
		return (InvestmentData) findById(id);
	}


	public InvestmentData persist(InvestmentData investmentData) {
		return (InvestmentData) persistEntity(investmentData);
	}

	public  List<InvestmentData> findInvestmentDataByUser() {
		Long uid = UserDataDAO.getLoggedInUserId();

		String qfilter = "userId==" + uid + "";

		PersistenceManager pm = getPersistenceManager();
		try {
			javax.jdo.Query query = pm.newQuery("select from " + InvestmentData.class.getName());
			query.setFilter(qfilter);
			List<InvestmentData> list = (List<InvestmentData>) query.execute();

			List<InvestmentData> r = (List<InvestmentData>) pm.detachCopyAll(list);

			return r;
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: investmentData.findinvestmentDataByUser(): qfilter=" + qfilter, e);
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return null;
	}

	public Boolean deleteInvestmentData(String id) {

		if (id == null) {
			return false;
		}
		PersistenceManager pm = getPersistenceManager();

		Long uid = UserDataDAO.getLoggedInUserId();
		Key key = KeyFactory.stringToKey(id);
		Boolean success = false;
		Transaction tx = pm.currentTransaction();
		try {

			InvestmentData e = pm.getObjectById(InvestmentData.class, key);
			if (e.getUserId() != uid) { // check owner
				log.severe("investmentItemData.remove() Error: Something weird going on in setting UID. e.getUserId()=" + e.getUserId() + " uid=" + uid);
				success = false;

			} else {
				tx.begin();
				pm.deletePersistent(e);
				tx.commit();
				success = true;
			}

		} catch (Exception e) {
			log.log(Level.SEVERE, "Error:", e);
			e.printStackTrace();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
				success = false;
			}
			pm.close();
		}

		return success;
	}

}